package com.jyxd.web.log;

import com.alibaba.fastjson.JSON;
import com.jyxd.web.data.user.User;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Objects;

@Aspect
@Component
public class MethodInvokeInterceptor {
    //本地异常日志记录对象
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 前置通知 用于拦截Controller层记录用户的操作
     *
     * @param joinPoint 切点
     */
    @Before("execution(* com.jyxd.web.controller.*.*.*(..)) || execution(* com.jyxd.web.*.controller.*.*(..))")
    public void doBefore(JoinPoint joinPoint) {
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        String className = joinPoint.getTarget().getClass().getName();
        String lastName = className.substring(className.lastIndexOf("."));
        HttpSession session = request.getSession();
        if(session != null) {
            User user = (User)session.getAttribute("user");
            if(user !=null) {
                MDC.put("userID",user.getId());
            }
        }
        logger.debug("@>>>>>>>>>>>>>>>>>类{}#########方法:{}#########url:{}", lastName, joinPoint.getSignature().getName(), request.getRequestURI());
        Object[] args = joinPoint.getArgs();
        if (null != args && args.length > 0) {
            for (int i = 0; i < args.length; i++) {
                if(null==args[i]||ClassTypeJudge.isBaseDataType(args[i].getClass())){
                    logger.debug(">>>参数[{}]: {}", i, args[i]);
                } else {
                    logger.debug(">>>参数[{}]: {}", i, JSON.toJSONString(args[i]));
                }
            }
        }
    }
}
